import os
import time
from datetime import datetime, timedelta

from celery import shared_task
from django.db.models import Count

from books.models import Book
from celery_task.celery import app


# @app.task
# def send_sms(mobile):
#     """发送短信"""
#     print("向手机号%s发送短信成功!" % mobile)
#     time.sleep(5)
#     return "send_sms OK"

@app.task
def create_report():
    # 获取每个非空作者及其书籍数量
    authors_books_count = Book.objects.exclude(author__isnull=True).values('author').annotate(books_count=Count('id'))
    # 打印结果
    for entry in authors_books_count:
        # print(f"作者: {entry['author']}, 当前作者出版书的数量: {entry['books_count']}")
        # 统计总书籍数量
        total_books_count = Book.objects.count()
        # print('书籍总数',total_books_count)
        content = {
            'authors_books': {entry['author']: entry['books_count'] for entry in authors_books_count},
            'total_books_count': total_books_count,
            'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }

        # 格式化字典内容
        content_str = ""
        for author, count in content['authors_books'].items():
            content_str += f"作者: {author}, 当前作者出版书的数量: {count}\n"
        content_str += f"总书籍数量: {content['total_books_count']}\n"
        content_str += f"报告生成时间: {content['date']}"

        print(content_str)
        # 写入txt文件
        try:
            # 写入txt文件
            with open('books_report.txt', 'w',encoding='utf-8') as file:
                file.write(content_str)
            print("文件写入成功")
        except Exception as e:
            print(f"文件写入失败: {e}")
    return True
